/**
 *  Copyright (C) 2008 Richard Hall
 *
 *  This program is free software; you can redistribute it and/or modify it under the terms of the 
 *  GNU General Public License as published by the Free Software Foundation; either version 3 of the 
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
 *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 *  See the GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along with this program; if not, 
 *  see <http://www.gnu.org/licenses>.
 *
 *  Additional permission under GNU GPL version 3 section 7
 *
 *  If you modify this Program, or any covered work, by linking or combining it with [name of library] 
 *  (or a modified version of that library), containing parts covered by the terms of 
 *  [name of library's license], the licensors of this Program grant you additional permission to 
 *  convey the resulting work. {Corresponding Source for a non-source form of such a combination shall 
 *  include the source code for the parts of [name of library] used as well as that of the 
 *  covered work.}
 *
 * 
 */

package com.gpsmedia.gui.frames;


import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;

import com.gpsmedia.audio.AudioPlayer;
import com.gpsmedia.dataobject.NmeaData;
/**
 * This class is used to select the audio data to be included. It allows playing
 * of the audio and setting of various parameters.
 * 
 * @author Richard Hall
 */

public class AudioFrame extends javax.swing.JFrame {

    private LinkedHashMap data;
    private NmeaData datarow = null;
    private Collection col;
    private Iterator it;
    private int currentLog;
    private AudioPlayer audioPlayer;
    private boolean audioPlaying;
    private ArrayList logoList = new ArrayList();
    private MainFrame frame = null;


    /**
	 * Constructor for this class.
	 * 
	 * @param data
	 *            LinkedHashMap containing NmeaData objects
         * @param showFrame
         *            Boolean true if Frame to be shown, false if not.  
         * @param mainFrame Put in as a work around to a problem with user access to the main frame. Can be set to null
         * if being used as part of the API. 
	 */
    public AudioFrame(LinkedHashMap data, boolean showFrame, MainFrame mainFrame) {
        if(mainFrame!=null){
            frame = mainFrame;
            frame.setVisible(false);
        }

        this.data = data;
        this.currentLog = 0;
        col = data.values();
        it = col.iterator();

        if(showFrame){
            ClassLoader loader = getClass().getClassLoader();
            URL fileLocation = loader.getResource("com/gpsmedia/images/earth_small.jpg");
            Image logo = Toolkit.getDefaultToolkit().getImage(fileLocation);
            logoList.add(logo);
            

            datarow = findNextAudio();
            if (datarow != null) {
                audioPlayer = new AudioPlayer(datarow.getAudio().getPath());
                initComponents();
                this.setVisible(true);
            } else {
                if(frame!=null){
                    frame.setVisible(true);
                }
                dispose();
            }
        }else{
            datarow = findNextAudio();
            
            while(datarow!=null){
                datarow.getAudio().setChecked(true);
                datarow.getAudio().setInclude(true);
                datarow.getAudio().setTitle(datarow.getDate().getTime().toString());
                datarow.getAudio().setDescription("");
                data.put(datarow.getDate(), datarow);
                datarow = findNextAudio();
            }
            if(frame!=null){
                frame.setVisible(true);
            }
            //frame = null;
            dispose();

        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnAdd = new javax.swing.JButton();
        btnRemove = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        txtTitle = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtDesc = new javax.swing.JTextArea();
        btnPlay = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setIconImages(logoList);
        setResizable(false);

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnRemove.setText("Remove");
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });

        jLabel1.setText("Audio Title");

        txtTitle.setText(datarow.getDate().getTime().toString());

        jLabel2.setText("Description");

        txtDesc.setColumns(20);
        txtDesc.setRows(5);
        jScrollPane1.setViewportView(txtDesc);

        btnPlay.setText("Play");
        btnPlay.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPlayActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtTitle, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(btnPlay)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnAdd)
                        .addGap(27, 27, 27)
                        .addComponent(btnRemove)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdd)
                    .addComponent(btnRemove)
                    .addComponent(btnPlay))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
	 * Button to add the audio
	 * 
	 * @param evt
	 */
    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        // TODO add your handling code here:
        if(btnPlay.getText().compareToIgnoreCase("Stop")==0){
            audioPlayer.stopMusic();
            btnPlay.setText("Play");
        }
        datarow.getAudio().setChecked(true);
        datarow.getAudio().setInclude(true);
        datarow.getAudio().setTitle(txtTitle.getText());
        datarow.getAudio().setDescription(txtDesc.getText());
        txtTitle.setText("");
        txtDesc.setText("");
        data.put(datarow.getDate(), datarow);
        datarow = null;
        datarow = findNextAudio();

        if (datarow != null) {
            changeAudio(datarow.getAudio().getPath());
            this.txtTitle.setText(datarow.getDate().getTime().toString());
            repaint();
        } else {
            if(frame!=null){
                frame.setVisible(true);
            }
            //frame = null;
            this.dispose();
        }
        
        
}//GEN-LAST:event_btnAddActionPerformed

    /**
	 * Change the path to the audio file
	 * 
	 * @param path
	 *            The path to the audio file
	 */
    public void changeAudio(String path) {
        audioPlayer = new AudioPlayer(path);
    }

    /**
	 * Button to remove the audio from being included
	 * 
	 * @param evt
	 */
    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
        // TODO add your handling code here:
        if(btnPlay.getText().compareToIgnoreCase("Stop")==0){
            audioPlayer.stopMusic();
            btnPlay.setText("Play");
        }
        
        datarow.getAudio().setChecked(true);
        datarow.getAudio().setInclude(false);
        txtTitle.setText("");
        txtDesc.setText("");
        data.put(datarow.getDate(), datarow);
        datarow = null;
        datarow = findNextAudio();

        if (datarow != null) {
            changeAudio(datarow.getAudio().getPath());
            this.txtTitle.setText(datarow.getDate().getTime().toString());
            repaint();
        } else {
            if(frame!=null){
                frame.setVisible(true);
            }
            frame = null;
            this.dispose();
            
        }
        
    }//GEN-LAST:event_btnRemoveActionPerformed

    /**
	 * Button to play/stop the audio from playing.
	 * 
	 * @param evt
	 */
    private void btnPlayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlayActionPerformed
        if (audioPlaying == false) {
            audioPlayer.playAudio();
            btnPlay.setText("Stop");
            audioPlaying = true;
        } else {
            audioPlayer.stopMusic();
            btnPlay.setText("Play");
            audioPlaying = false;
        }
    // TODO add your handling code here:
}//GEN-LAST:event_btnPlayActionPerformed

    /**
	 * Returns the NmeaData object for the next piece of audio to be checked.
	 * 
	 * @return NmeaData object
	 */
    public NmeaData findNextAudio() {
        boolean found = false;
        NmeaData tempData = null;
        int i = 0;
        while (it.hasNext() && found == false) {
            tempData = (NmeaData) it.next();
            if (tempData.getAudio().getPath().compareToIgnoreCase("") != 0 &&
                    tempData.getAudio().isChecked() == false) {
                found = true;
            } else {
                tempData = null;
            }
        }
        return tempData;

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnPlay;
    private javax.swing.JButton btnRemove;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtDesc;
    private javax.swing.JTextField txtTitle;
    // End of variables declaration//GEN-END:variables

}
